import { Component, OnInit, Input } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import { NzModalSubject } from 'ng-zorro-antd';

import { UsersService } from '../../services';
import { LocalstoreService } from '../../../shared/services';

@Component({
  selector: 'ege-edit-user-form',
  templateUrl: './edit-user-form.component.html',
  styleUrls: ['./edit-user-form.component.scss']
})
export class EditUserFormComponent implements OnInit {

  isConfirmLoading = false;

  _data: any;
  validateForm: FormGroup;

  token = this.localstorageService.getItem('USER_TOKEN');

  @Input()
  set user(value: any) {
    this._data = value;
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[ i ].markAsDirty();
      }
    }

    if (this.validateForm.valid) {
      this.isConfirmLoading = true;

      // console.log(this.validateForm.value);
      // console.log(this._data);

      const userId = this._data.id;
      const value = this.validateForm.value;

      this.usersService
        .editUser(userId, value, this.token.id).subscribe(result => {
          // console.log(result);
          this.emitDataOutside(result);
        }, error => {
          this.isConfirmLoading = false;
        });
    }
  }

  emitDataOutside(result) {
    this.isConfirmLoading = false;
    this.subject.next(result);
    this.subject.next('onOk');
  }

  handleCancel(e) {
    this.subject.destroy('onCancel');
  }

  constructor(
    private fb: FormBuilder,
    private subject: NzModalSubject,
    private usersService: UsersService,
    private localstorageService: LocalstoreService,
  ) { }

  ngOnInit() {
    this.validateForm = this.fb.group({
      username         : [ this._data.username, [ Validators.required ] ],
      email            : [ this._data.email, [ Validators.email ] ],
      realname         : [ this._data.realname ],
      realm            : [ this._data.realm ],
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }
}
